﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using Project.Core.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Project.Core.Api.Controllers
{
    /// <summary>
    /// 通用方法的控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class BaseController : Controller
    {
        private IHostingEnvironment _hostingEnv;
        string[] TypeFormat = { "png", "jpg", "jpeg", "gif", "ico" };
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Env"></param>
        public BaseController(IHostingEnvironment Env) {
            _hostingEnv = Env;
        }
        /// <summary>
        /// 上传图片方法1
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadImg1")]
        public async Task<IActionResult> UploadImg1() {
            var files = Request.Form.Files;
            var size = files.Sum(f => f.Length);
            string filePath111 = _hostingEnv.WebRootPath + $@"\Files\Pictures\" + $@"\{DateTime.Now.Year}" + $@"\{DateTime.Now.Date}" + $@"\{DateTime.Now.Day}";
            if (size > 1024 * 1024 * 100)
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "文件总大小不得大于100M!",
                    Success = false,
                    Total = 0,
                });
            }
            if (size == 0)
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "请选择文件!",
                    Success = false,
                    Total = 0,
                });
            }
            List<string> filePathResultList = new List<string>();
            foreach (var item in files) {
                var fileName = ContentDispositionHeaderValue.Parse(item.ContentDisposition).FileName.Trim('"');
                //获取项目的wwwroot文件地址
                //string filePath = _hostingEnv.WebRootPath + $@"\Files\Pictures\" + $@"\{DateTime.Now.Year}" + $@"\{DateTime.Now.Date}" + $@"\{DateTime.Now.Day}";
                string filePath = _hostingEnv.WebRootPath + @"\Files\Pictures" + $@"\{DateTime.Now.Year}" + $@"\{DateTime.Now.Date}" + $@"\{DateTime.Now.Day}";
                if (!Directory.Exists(filePath)) {
                    Directory.CreateDirectory(filePath);
                }
                string fileType = fileName.Split('.')[1];
                if (!TypeFormat.Contains(fileType)) {
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "仅支持jpg、png、jpeg、ico、gif格式的图片!",
                        Success = false,
                        Total = 0,
                    });
                }
                fileName = Guid.NewGuid() + "." + fileType;
                string fileFullName = filePath + fileName;
                //什么鬼？System被占用了吗？？？？？？？
                //using (FileStream fs = System.IO.File.Create(fileFullName))
                //{
                //    item.CopyTo(fs);
                //    fs.Flush();
                //}
                using (FileStream fs = new FileStream(fileFullName,FileMode.CreateNew))
                {
                    await item.CopyToAsync(fs);
                }
                filePathResultList.Add(fileFullName);
            }
            return Ok(new ReturnMsg
            {
                Data = filePathResultList,
                Msg = "上传成功!",
                Success = true,
                Total = filePathResultList.Count(),
            });
        }

        /// <summary>
        /// 上传图片方法2
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadImg2")]
        public async Task<IActionResult> UploadImg2(List<IFormFile> fileinput)
        {
            //string filePath111 = _hostingEnv.WebRootPath + $@"\Files\Pictures" + $@"\{DateTime.Now.Year}" + $@"\{DateTime.Now.Date}" + $@"\{DateTime.Now.Day}";
            var size = fileinput.Sum(f => f.Length);
            if (size > 1024 * 1024 * 100)
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "文件总大小不得大于100M!",
                    Success = false,
                    Total = 0,
                });
            }
            if (size == 0)
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "请选择文件!",
                    Success = false,
                    Total = 0,
                });
            }
            List<string> filePathResultList = new List<string>();
            foreach (var item in fileinput)
            {
                //获取项目的wwwroot文件地址
                //string fileFullName = _hostingEnv.WebRootPath + @"\Files\Pictures" + $@"\{item.FileName}";
                string fileFullName = _hostingEnv.WebRootPath + @"\Files\Pictures" + $@"\{DateTime.Now.Year}" + $@"\{DateTime.Now.Date}" + $@"\{DateTime.Now.Day}" + $@"\{item.FileName}";
                string filePath = _hostingEnv.WebRootPath + @"\Files\Pictures" + $@"\{DateTime.Now.Year}" + $@"\{DateTime.Now.Date}" + $@"\{DateTime.Now.Day}";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string fileType = item.FileName.Split('.')[1];
                if (!TypeFormat.Contains(fileType))
                {
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "仅支持jpg、png、jpeg、ico、gif格式的图片!",
                        Success = false,
                        Total = 0,
                    });
                }
                //后面在研究，先试试下面的方法行不行
                //using (FileStream fs = System.IO.File.Create(fileFullName))
                //{
                //    item.CopyTo(fs);
                //    fs.Flush();
                //}
                using (FileStream fs = new FileStream(fileFullName, FileMode.CreateNew))
                {
                    await item.CopyToAsync(fs);
                }
                filePathResultList.Add(fileFullName);
            }
            return Ok(new ReturnMsg
            {
                Data = filePathResultList,
                Msg = "上传成功!",
                Success = true,
                Total = filePathResultList.Count(),
            });
        }
    }
}